/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Telas;

import Beans.BeanCidade;
import Beans.BeanPlanoSaude;
import CRUD.CRUDCidade;
import CRUD.CRUDPlanoSaude;
import ClassesExtras.LetrasMaiusculas;
import Conexao.ConexaoBanco;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Marcos
 */
public class Jp_CadastroPlanoSaude extends javax.swing.JPanel {

    DefaultTableModel TMPlanoSaude = new DefaultTableModel(null, new String[]{"Código", "Plano de Saúde"}) {// Faz a sobreposição de método e permite tbm a instancia de classe abstrata, quando implementado seus métodos
        @Override
        public boolean isCellEditable(int row, int column) {
            return false; //Não deixar editar uma linha da JTable
//            return super.isCellEditable(row, column);
        }
    };
    public Connection conexao;
    Object[] btSimNao = {"Sim", "Não"};
    List<BeanPlanoSaude> ListaPlanoSaude;

    /**
     * Creates new form Jp_CadastroPlanoSaude
     */
    public Jp_CadastroPlanoSaude() throws SQLException {
        initComponents();
        AlinhaColunaJTable();
        this.conexao = ConexaoBanco.getConexao();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelCodigo = new javax.swing.JLabel();
        jTextFieldCodigo = new javax.swing.JTextField();
        jLabelPlanoSaude = new javax.swing.JLabel();
        jTextFieldPlanoSaude = new LetrasMaiusculas();
        jButtonIncluir = new javax.swing.JButton();
        jButtonAlterar = new javax.swing.JButton();
        jButtonExcluir = new javax.swing.JButton();
        jLabelBarraStatus = new javax.swing.JLabel();
        jLabelCamposObrigatorios = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableConsultaPlanoSaude = new javax.swing.JTable();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabelCodigo.setText("Código:");

        jTextFieldCodigo.setEnabled(false);

        jLabelPlanoSaude.setText("*Plano de Saúde:");

        jTextFieldPlanoSaude.setVerifyInputWhenFocusTarget(false);
        jTextFieldPlanoSaude.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextFieldPlanoSaudeKeyPressed(evt);
            }
        });

        jButtonIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Incluir.png"))); // NOI18N
        jButtonIncluir.setMnemonic('I');
        jButtonIncluir.setText("Incluir");
        jButtonIncluir.setToolTipText("Incluir");
        jButtonIncluir.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                jButtonIncluirMouseDragged(evt);
            }
        });
        jButtonIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonIncluirActionPerformed(evt);
            }
        });

        jButtonAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Alterar.png"))); // NOI18N
        jButtonAlterar.setMnemonic('A');
        jButtonAlterar.setText("Alterar");
        jButtonAlterar.setToolTipText("Alterar");
        jButtonAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarActionPerformed(evt);
            }
        });

        jButtonExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/Excluir.png"))); // NOI18N
        jButtonExcluir.setMnemonic('E');
        jButtonExcluir.setText("Excluir");
        jButtonExcluir.setToolTipText("Excluir");
        jButtonExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExcluirActionPerformed(evt);
            }
        });

        jLabelBarraStatus.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabelBarraStatus.setForeground(new java.awt.Color(255, 0, 51));

        jLabelCamposObrigatorios.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
        jLabelCamposObrigatorios.setText("* Campos Obrigatórios a serem preechidos");

        jTableConsultaPlanoSaude.setModel(TMPlanoSaude);
        jTableConsultaPlanoSaude.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableConsultaPlanoSaudeMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableConsultaPlanoSaude);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelCodigo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabelPlanoSaude)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldPlanoSaude, javax.swing.GroupLayout.DEFAULT_SIZE, 434, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabelBarraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 426, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelCamposObrigatorios))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelCodigo)
                    .addComponent(jLabelPlanoSaude)
                    .addComponent(jTextFieldPlanoSaude, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAlterar)
                    .addComponent(jButtonIncluir)
                    .addComponent(jButtonExcluir))
                .addGap(7, 7, 7)
                .addComponent(jLabelBarraStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelCamposObrigatorios)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTextFieldPlanoSaudeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldPlanoSaudeKeyPressed
        if (!"".equals(jTextFieldPlanoSaude.getText())) {
        } else {
            jTextFieldPlanoSaude.setBackground(new Color(255, 255, 255));
        }
        try {
            listaplanosaude();
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroPlanoSaude.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroPlanoSaude.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jTextFieldPlanoSaudeKeyPressed

    private void jButtonIncluirMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButtonIncluirMouseDragged
        //jButtonIncluir.setLocation(jButtonIncluir.getX() + evt.getX(), jButtonIncluir.getY() + evt.getY());
    }//GEN-LAST:event_jButtonIncluirMouseDragged

    private void jButtonIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIncluirActionPerformed
        if (jTextFieldPlanoSaude.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O campo plano de saúde precisa ser preenchido!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jTextFieldPlanoSaude.setBackground(new Color(255, 204, 204));
            jTextFieldPlanoSaude.grabFocus();
        } else {
            validaplanosaudeadiciona();
        }
    }//GEN-LAST:event_jButtonIncluirActionPerformed

    private void jTableConsultaPlanoSaudeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableConsultaPlanoSaudeMouseClicked
        if (evt.getClickCount() == 2) {
            carregardados();
        }
    }//GEN-LAST:event_jTableConsultaPlanoSaudeMouseClicked

    private void jButtonAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarActionPerformed
        if ("".equals(jTextFieldCodigo.getText())) {
            JOptionPane.showMessageDialog(null, "Selecione um plano de saúde para ser alterado!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jTableConsultaPlanoSaude.grabFocus();
        } else if (jTextFieldPlanoSaude.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "O campo plano de saúde precisa ser preenchido!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jTextFieldPlanoSaude.setBackground(new Color(255, 204, 204));
            jTextFieldPlanoSaude.grabFocus();
        } else {
            validaplanosaudealtera();
        }
    }//GEN-LAST:event_jButtonAlterarActionPerformed

    private void jButtonExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExcluirActionPerformed
        if ("".equals(jTextFieldCodigo.getText())) {
            JOptionPane.showMessageDialog(null, "Selecione um plano de saúde para ser excluído!", "Atenção", JOptionPane.WARNING_MESSAGE);
            jTableConsultaPlanoSaude.grabFocus();
        } else {
            int i = JOptionPane.showOptionDialog(this, "Deseja remover o plano de saúde?", "Confirmação", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, btSimNao, btSimNao[1]);
            if (i == JOptionPane.YES_OPTION) {
                remove();
            }
        }
    }//GEN-LAST:event_jButtonExcluirActionPerformed
    public void listaplanosaude() throws SQLException, ParseException {
        CRUDPlanoSaude CRUDPlanoSaude = new CRUDPlanoSaude();
        ListaPlanoSaude = CRUDPlanoSaude.getListaPlanoSaudeDen("%" + jTextFieldPlanoSaude.getText() + "%");
        mostraPlanoSaude(ListaPlanoSaude);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAlterar;
    private javax.swing.JButton jButtonExcluir;
    private javax.swing.JButton jButtonIncluir;
    private javax.swing.JLabel jLabelBarraStatus;
    private javax.swing.JLabel jLabelCamposObrigatorios;
    private javax.swing.JLabel jLabelCodigo;
    private javax.swing.JLabel jLabelPlanoSaude;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableConsultaPlanoSaude;
    public javax.swing.JTextField jTextFieldCodigo;
    public javax.swing.JTextField jTextFieldPlanoSaude;
    // End of variables declaration//GEN-END:variables

    public void limpardados() {
        jTextFieldCodigo.setText(null);
        jTextFieldPlanoSaude.setText(null);
    }

    private void AlinhaColunaJTable() {
        int col = 0;
        jTableConsultaPlanoSaude.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Selecionar somente uma linha da JTable
        jTableConsultaPlanoSaude.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); //barra horizontal na JTable 
        jTableConsultaPlanoSaude.getColumnModel().getColumn(col++).setPreferredWidth(135); // Acertar Tamanho de cada coluna
        jTableConsultaPlanoSaude.getColumnModel().getColumn(col++).setPreferredWidth(475);
    }

    public void carregardados() {
        jTextFieldCodigo.setText(String.valueOf(ListaPlanoSaude.get(jTableConsultaPlanoSaude.getSelectedRow()).getCod_plano_saude()));
        jTextFieldPlanoSaude.setText(ListaPlanoSaude.get(jTableConsultaPlanoSaude.getSelectedRow()).getDen_plano_saude());
    }
    
    public void validaplanosaudealtera() {
        String plano_saude = jTextFieldPlanoSaude.getText().trim();
        String sql = "select den_plano_saude from plano_saude where den_plano_saude = ?";
        try {
            PreparedStatement stmt = this.conexao.prepareStatement(sql);
            stmt.setString(1, plano_saude);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                JOptionPane.showMessageDialog(null, "Plano de saúde já cadastrado!", "Atenção", JOptionPane.WARNING_MESSAGE);
                limpardados();
                listaplanosaude();
            } else {
                altera();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Fr_Principal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroCidade.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void validaplanosaudeadiciona() {
        String plano_saude = jTextFieldPlanoSaude.getText().trim();
        String sql = "select den_plano_saude from plano_saude where den_plano_saude = ?";
        try {
            PreparedStatement stmt = this.conexao.prepareStatement(sql);
            stmt.setString(1, plano_saude);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                JOptionPane.showMessageDialog(null, "Plano de saúde já cadastrado!", "Atenção", JOptionPane.WARNING_MESSAGE);
                limpardados();
                listaplanosaude();
            } else {
                cadastro();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Fr_Principal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroCidade.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void cadastro() {
        try {
            BeanPlanoSaude BPS = new BeanPlanoSaude();
            //BPS.setCod_plano_saude(Integer.valueOf(jTextFieldCodigo.getText()));
            BPS.setDen_plano_saude(jTextFieldPlanoSaude.getText());
            CRUDPlanoSaude dao = new CRUDPlanoSaude();
            dao.adiciona(BPS);
            limpardados();
            listaplanosaude();
            jLabelBarraStatus.setText("Incluido com sucesso!!!");
            threadR(jLabelBarraStatus);


        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroPessoa.class
                    .getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroPlanoSaude.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void altera() {
        BeanPlanoSaude BPS = new BeanPlanoSaude();
        BPS.setCod_plano_saude(Integer.valueOf(jTextFieldCodigo.getText()));
        BPS.setDen_plano_saude(jTextFieldPlanoSaude.getText());
        CRUDPlanoSaude dao = null;

        try {
            dao = new CRUDPlanoSaude();
            dao.altera(BPS);
            jLabelBarraStatus.setText("Alterado com sucesso!!!");
            limpardados();
            listaplanosaude();
            threadR(jLabelBarraStatus);
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroPlanoSaude.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroPlanoSaude.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void remove() {
        BeanPlanoSaude BPS = new BeanPlanoSaude();
        BPS.setCod_plano_saude(Integer.valueOf(jTextFieldCodigo.getText()));
        BPS.setDen_plano_saude(jTextFieldPlanoSaude.getText());        
        CRUDPlanoSaude dao = null;

        try {
            dao = new CRUDPlanoSaude();
            dao.remove(BPS);
            jLabelBarraStatus.setText("Excluído com sucesso!!!");
            limpardados();
            listaplanosaude();
            threadR(jLabelBarraStatus);
        } catch (SQLException ex) {
            Logger.getLogger(Jp_CadastroPlanoSaude.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Jp_CadastroPlanoSaude.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void threadR(final JLabel label) {
        Thread tThread = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
                //repaint();    
                label.setText("");

            }
        });
        tThread.start();
    }

    private void mostraPlanoSaude(List<BeanPlanoSaude> ListaPlanoSaude) {
        if (TMPlanoSaude == null) {
            JOptionPane.showMessageDialog(null, "teste");
        } else {
            while (TMPlanoSaude.getRowCount() > 0) {
                TMPlanoSaude.removeRow(0);
            }
            if (ListaPlanoSaude.size() < 1) {
                //JOptionPane.showMessageDialog(null, "teste2");
            } else {
                String[] linha = new String[]{null, null};
                for (int i = 0; i < ListaPlanoSaude.size(); i++) {
                    TMPlanoSaude.addRow(linha);
                    TMPlanoSaude.setValueAt(ListaPlanoSaude.get(i).getCod_plano_saude(), i, 0);
                    TMPlanoSaude.setValueAt(ListaPlanoSaude.get(i).getDen_plano_saude(), i, 1);
                }
            }
        }
    }
}
